<template>
  <div>
    <div class="iSearch-box" :style="{width: boxWidth + 'px'}">
      <div v-for="(x, index) in filterList" :key="index">
        <el-input @keyup.enter.native="onclick" clearable size="small" v-if="x.type === 'input'" :placeholder="x.placeholder" v-model="x.val" :style="{width: inputWidth + 'px'}"></el-input>
          <el-select filterable :loading="loading" size="small" v-else-if="(x.type === 'select' && auth) || x.type === 'select-net'" v-model="x.val" :placeholder="x.placeholder" :style="{width: inputWidth + 'px'}" clearable>
            <el-option
              v-for="item in x.list"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        <el-date-picker size="small" v-else-if="x.type === 'Month'"
          v-model="x.val" :style="{width: inputWidth + 'px'}"
          type="month"
          placeholder="选择月">
        </el-date-picker>
        <el-date-picker size="small" v-else-if="x.type === 'time'"
          v-model="x.val"
          type="datetime" :style="{width: 260 + 'px'}"
          range-separator="至"
          :start-placeholder="x.startPlaceholder"
          :end-placeholder="x.endPlaceholder">
        </el-date-picker>
        <!-- type="datetimerange" 开启日期加时间选择器。 => formatDate(DATE, type=2) -->
        <el-date-picker size="small" v-else-if="x.type === 'dateTiem'"
          v-model="x.val"
          type="daterange" :style="{width: 260 + 'px'}"
          :picker-options="pickerOptions"
          range-separator="至"
          :start-placeholder="x.startPlaceholder"
          :end-placeholder="x.endPlaceholder"
          :default-time="['00:00:00', '00:00:00']"
          align="right">
        </el-date-picker>
        <el-date-picker size="small" v-else-if="x.type === 'onlyTime'"
          v-model="x.val"
          type="date" :style="{width: inputWidth + 'px'}"
          :placeholder="x.placeholder">
        </el-date-picker>
        <el-date-picker size="small" v-else-if="x.type === 'year'"
          v-model="x.val"
          type="year"
          placeholder="选择年">
        </el-date-picker>
        <!-- 级联选择器 -->
        <el-cascader size="small" placeholder="请选择区域" :props="{ checkStrictly: true }" v-else-if="x.type === 'district'" :style="{width: inputWidth + 'px'}" v-model="x.val"
          :options="x.list" filterable
          clearable></el-cascader>
          <el-cascader size="small" :placeholder="x.placeholder" :props="{ label: 'name', value: 'id', checkStrictly: true  }" v-else-if="x.type === 'tree'" :style="{width: inputWidth + 'px'}" v-model="x.val"
          :options="x.list" filterable
          clearable></el-cascader>
          <!-- 自定义数据区间选择器 -->
        <el-row v-else-if="x.type === 'section'" style="width: 200px;margin-right: 8px">
          <el-col :span="11"><el-input type="number" v-model.number="x.val[0]" :placeholder="x.startPlaceholder"></el-input></el-col>
          <el-col :span="2" style="text-align: center">~</el-col>
          <el-col :span="11"><el-input type="number" v-model.number="x.val[1]" :placeholder="x.endPlaceholder"></el-input></el-col>
        </el-row>
        &nbsp;
      </div>
      <!-- 信息重置 -->
      <div v-if="reset && filterList && filterList.length">
        <el-button size="small" @click="onclickcancel" icon="el-icon-close">重置</el-button>&nbsp;
      </div>
      <!-- 搜索按钮 -->
      <div v-if="filterList && filterList.length">
        <el-button size="small" icon="el-icon-search" type="primary" @click="onclick">查询</el-button>&nbsp;
      </div>
      <!-- 导出 excel -->
      <div v-if="ep && filterList && filterList.length">
        <el-button size="small" type="primary" icon="el-icon-upload" @click="exportExcel">导出</el-button>&nbsp;
      </div>
    </div>
  </div>
</template>

<script>
import { CLONEDEEP, formatDate } from '../util/util'
import { _SelectNet } from '../api/api'
export default {
  data () {
    return {
      loading: false,
      selectToken: false,
      filterList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              const end = new Date(new Date().toDateString())
              const start = new Date(new Date().toDateString())
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三天',
            onClick (picker) {
              const end = new Date(new Date().toDateString())
              const start = new Date(new Date().toDateString())
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date(new Date().toDateString())
              const start = new Date(new Date().toDateString())
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date(new Date().toDateString())
              const start = new Date(new Date().toDateString())
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }]
      }
    }
  },
  props: {
    list: {
      type: Array,
      default () {
        return []
      }
    },
    boxWidth: Number,
    inputWidth: Number,
    ep: {
      type: Boolean,
      default: false
    },
    reset: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    auth () {
      return parseInt(window.sessionStorage.getItem('auth'))
    }
  },
  async created () {
    // 要深度克隆 引用数据类型后。再对克隆数据进行调整修改 不然会导致组件直接修改props的情况
    let list = CLONEDEEP(this.list)
    if (!list) list = []
    const filterList = []
    for (const ele of list) {
      if (ele.type === 'select' && ele.list !== undefined) {
        ele.list = ele.list.map(el => ({ label: el[ele.key], value: el[ele.value] }))
      }
      if (ele.type === 'select-net' && ele.url !== undefined) {
        this.loading = true
        // 需要发送请求获取实时数据的select下拉框
        const data = await _SelectNet(ele.url)
        if (data.success) {
          ele.list = data.data || []
          if (ele.params) ele.list = data[ele.params]
          // 数据以展示: filterList 中的 key 和 value 的值 映射到 真实的select组件的 label 和 value 中
          ele.list = ele.list.map(el => ({ label: el[ele.key], value: el[ele.value] }))
          this.loading = false
        } else {
          this.$message.error(data.info)
        }
      }
      if (ele.type === 'tree') {
        // const { data } = await api.get(ele.url, {})
        // ele.list = data || []
        // ele.list = api.handconstree(ele.list)
      }
      // 自定义数据 区间选择器  给他初始化 val
      if (ele.type === 'section') {
        ele.val = ['', '']
      }
      if (ele.defaultDate) { // 默认时间,往前推30天
        ele.val = [new Date(new Date().getTime() - (30 * 3600 * 24 * 1000)), new Date()]
      }
      // 初始化 val
      ele.val = ''
      ele.placeholder = ele.placeholder ? ele.placeholder : ''
      ele.startPlaceholder = ele.startPlaceholder ? ele.startPlaceholder : ''
      ele.endPlaceholder = ele.endPlaceholder ? ele.endPlaceholder : ''
      // 处理完毕的每个item 都加入 filterList 中
      filterList.push(ele)
    }
    // 最好 把整理好的数据 载入组件自身data里。然后可以开始渲染节点了。
    this.filterList = filterList
  },
  methods: {
    // 重置输入框
    onclickcancel () {
      for (let i = 0; i < this.filterList.length; i++) {
        this.filterList[i].val = this.filterList[i].default !== undefined ? this.filterList[i].default : ''
        if (this.filterList[i].type === 'section') this.filterList[i].val = ['', '']
        if (this.filterList[i].defaultDate) this.filterList[i].val = [new Date(new Date().getTime() - (30 * 3600 * 24 * 1000)), new Date()]
      }
      this.onclick()
    },
    // 点击索引
    // 本质上就是把所有各种input里面的数据打包，发送给父组件， 父组件用这个数据发送请求
    onclick () {
      const d = CLONEDEEP(this.filterList)
      const arr = []
      d.forEach(ele => {
        /* key是关键 key就是父组件传的 filterList 中每项的name  */
        /* 父组件搜索时， 需要key来当index 并用searchArr更新掉 全局数据 再通过 getList拿数据 */
        if (ele.type === 'tree') {
          arr.push({ key: ele.name, val: ele.val[ele.val.length - 1] })
        } else if (ele.type === 'section') {
          /* ceil向前取整 => 0.1 = 1  ---  floor向后取整 => 0.1 = 0 */
          arr.push({ key: 'leftQty', val: Math.ceil(ele.val[0]) > 0 ? Math.ceil(ele.val[0]) : undefined })
          arr.push({ key: 'rightQty', val: Math.floor(ele.val[1]) > 0 ? Math.ceil(ele.val[1]) : undefined })
        } else if (ele.type === 'onlyTime') {
          if (ele.val) {
            arr.push({ key: ele.name, val: formatDate(ele.val) })
          } else {
            arr.push({ key: ele.name, val: undefined })
          }
        } else if (ele.type === 'time') {
          if (ele.val) {
            arr.push({ key: 'startdate', val: formatDate(ele.val[0], 2) })
            arr.push({ key: 'enddate', val: formatDate(ele.val[1], 2) })
          } else {
            arr.push({ key: 'startdate', val: undefined })
            arr.push({ key: 'enddate', val: undefined })
          }
        } else if (ele.type === 'dateTiem') {
          if (ele.val) {
            arr.push({ key: ele.startName, val: formatDate(ele.val[0]) })
            arr.push({ key: ele.endName, val: formatDate(ele.val[1]) })
          } else {
            arr.push({ key: ele.startName, val: undefined })
            arr.push({ key: ele.endName, val: undefined })
          }
        } else {
          /* 其余得 input 没值又有默认值属性就使用默认值。 */
          if (ele.default !== undefined && ele.val === '') {
            ele.val = ele.default
          }
          /* 有啥值就用啥值 */
          arr.push({ key: ele.name, val: ele.val })
        }
      })
      this.$emit('setQuery', arr)
    },
    // 导出 excel
    exportExcel () {
      const d = CLONEDEEP(this.filterList)
      const arr = []
      d.forEach(ele => {
        /* key是关键 key就是父组件传的 filterList 中每项的name  */
        /* 父组件搜索时， 需要key来当index 并用searchArr更新掉 全局数据 再通过 getList拿数据 */
        if (ele.type === 'tree') {
          arr.push({ key: ele.name, val: ele.val[ele.val.length - 1] })
        } else if (ele.type === 'section') {
          /* ceil向前取整 => 0.1 = 1  ---  floor向后取整 => 0.1 = 0 */
          arr.push({ key: 'leftQty', val: Math.ceil(ele.val[0]) > 0 ? Math.ceil(ele.val[0]) : undefined })
          arr.push({ key: 'rightQty', val: Math.floor(ele.val[1]) > 0 ? Math.ceil(ele.val[1]) : undefined })
        } else if (ele.type === 'onlyTime') {
          if (ele.val) {
            arr.push({ key: ele.name, val: formatDate(ele.val) })
          } else {
            arr.push({ key: ele.name, val: undefined })
          }
        } else if (ele.type === 'time') {
          if (ele.val) {
            arr.push({ key: 'startdate', val: formatDate(ele.val[0], 2) })
            arr.push({ key: 'enddate', val: formatDate(ele.val[1], 2) })
          } else {
            arr.push({ key: 'startdate', val: undefined })
            arr.push({ key: 'enddate', val: undefined })
          }
        } else if (ele.type === 'dateTiem') {
          if (ele.val) {
            arr.push({ key: ele.startName, val: formatDate(ele.val[0], 2) })
            arr.push({ key: ele.endName, val: formatDate(ele.val[1], 2) })
          } else {
            arr.push({ key: ele.startName, val: undefined })
            arr.push({ key: ele.endName, val: undefined })
          }
        } else {
          /* 其余得 input 没值又有默认值属性就使用默认值。 */
          if (ele.default !== undefined && ele.val === '') {
            ele.val = ele.default
          }
          /* 有啥值就用啥值 */
          arr.push({ key: ele.name, val: ele.val })
        }
      })
      this.$emit('exportExcel', arr)
    }
  },
  watch: {
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.iSearch-box{
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-right: 15px;
}
.el-form-item {
  margin-bottom: 0px;
}
</style>
